class StoreController < ApplicationController
  def index
    if params[:search].nil?
      @products=Product.find_products_for_sale
      @cart=find_cart
    else
      @products=Product.search_products_for_sale(params[:search])
      @cart=find_cart
    end
    @time_now = Time.now.strftime("%a %d %B %Y")
    @page_title = "Jasoet Pragmatic Bookshelf"
  end

  def add_to_cart
    product = Product.find(params[:id])
    @cart = find_cart
    @current_item = @cart.add_product(product)
    respond_to do |format|
      format.js if request.xhr?
      format.html {redirect_to_index}
    end
  rescue ActiveRecord::RecordNotFound
    logger.error("Attempt to access invalid product #{params[:id]}" )
    redirect_to_index "Invalid Product"
  end

  def remove_to_cart
    product = Product.find(params[:id])
    @cart = find_cart
    @current_item=@cart.remove_product(product)
    respond_to do |format|
      format.js if request.xhr?
      format.html {redirect_to_index}
    end
#    if @current_item.nil?
#      render :update do |page|
#        page.replace_html("cart", :partial => "cart", :object => @cart)
#      end
#    else
#      render :update do |page|
#        page.replace_html("cart", :partial => "cart", :object => @cart)
#
#        page[:current_item].visual_effect :highlight,
#                                          :startcolor => "#88ff88",
#                                          :endcolor => "#114411"
#      end
#    end
  rescue ActiveRecord::RecordNotFound
    logger.error("Attempt to access invalid product #{params[:id]}" )
    redirect_to_index "Invalid Product"
  end

  def empty_cart
    session[:cart] = nil
    @cart = find_cart
    respond_to do |format|
      format.js if request.xhr?
      format.html {redirect_to_index}
    end
  end

  def back_to_index
    redirect_to :action => :index
  end

  private
  def find_cart
    session[:cart] ||= Cart.new
  end

  def redirect_to_index(msg = nil)
    flash[:notice] = msg if msg
    redirect_to :action => 'index'
  end

end
